<?php


namespace App\Http\Middleware;

use Closure;
use D1M\Common\Exceptions\AuthFailedException;
use D1M\Common\Exceptions\BusinessException;
use App\Exceptions\JavaApiException;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;


class AuthApi
{
    public function handle(Request $request, Closure $next)
    {
        $this->jwtToken($request);
        return $next($request);
    }

    private function jwtToken($request)
    {
        if (!$request->hasHeader('Authorization')) {
            throw new AuthFailedException('Authorization header missing',-1002);
            //return response()->json(['error' => 'Authorization header missing'], 401);
        }

        $header = $request->header('Authorization');
        $jwt = trim(str_replace('Bearer', '', $header));

        if(!$jwt){
            throw new AuthFailedException('token not found',-1002);
            //return response()->json(['error' => 'JWT not found'], 400);
        }
        try {
            $decodedToken = JWT::decode($jwt, env('JWT_KEY'), ["HS256"]);
        } catch (ExpiredException $e) { // token过期
            throw new JavaApiException('token失效～',-1002);
            //throw new AuthFailedException('token失效～',-1002);
        }catch (\Exception $e) {
            throw new AuthFailedException($e->getMessage(),-1002);
        }
        if(!$decodedToken->uid){
            throw new AuthFailedException('token异常',-1002);
        }
        if($decodedToken->uid !=env("PAWHUB_APP_ID")) {
            throw new AuthFailedException('appid不匹配',-1004);
        }
        $redisKey = 'pos:jwt_login:token:'.$decodedToken->uid;
        $redis = Redis::get($redisKey);
        if(!$redis || $redis !=$jwt){
            throw new AuthFailedException('token失效',-1002);
        }
        $this->checkSign($request,$jwt);
    }

    //验证签名
    private function checkSign($request,$token)
    {
        $nonce = $request->get('nonce');
        $timestamp = $request->get('timestamp');
        $signature = $request->get('signature');


        $params = [
            'nonce'     => $nonce,
            'token' => $token,
            'timestamp'    => $timestamp,
            'appid'          => env("PAWHUB_APP_ID"),
            'secret'          => env("PAWHUB_APP_SECRET"),
            //'data' =>$data
        ];
        if($request->post('data')){
            $params['data'] = json_encode($request->post('data'),JSON_UNESCAPED_UNICODE);
//            if($params['data']==='{"store_id":null}'){
//                $params['data']= '{"store_id":""}';
//            }
            Log::info('签名入参：'.$params['data']);
        }


        ksort($params);
        $keyValues = [];
        foreach ($params as $key => $value) {
            //if($value!==null){
//            if ($key == 'public_key' || $key == 'private_key'){
//                $value = stripslashes($value);
//            }
            $keyValues[] = "{$key}=$value";
            //}
        }

        $str = implode('&', $keyValues);
        Log::info('签名字串：'.$str);
        $str = stripslashes($str);
        $str = sha1($str);
        Log::info('签名结果：'.$str);
        //dump($str);
        if( $str != $signature ){
            throw new AuthFailedException("验签失败",-1003);
        }
    }
}